package com.enjoylearning.content.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.enjoylearning.base.exception.CommonError;
import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.content.config.MultipartSupportConfig;
import com.enjoylearning.content.feignClient.MediaServiceClient;
import com.enjoylearning.content.mapper.CourseBaseMapper;
import com.enjoylearning.content.mapper.CourseMarketMapper;
import com.enjoylearning.content.mapper.CoursePublishMapper;
import com.enjoylearning.content.mapper.CoursePublishPreMapper;
import com.enjoylearning.content.model.dto.CourseBaseInfoDto;
import com.enjoylearning.content.model.dto.CoursePreviewDto;
import com.enjoylearning.content.model.dto.TeachplanDto;
import com.enjoylearning.content.model.po.CourseMarket;
import com.enjoylearning.content.model.po.CoursePublish;
import com.enjoylearning.content.model.po.CoursePublishPre;
import com.enjoylearning.content.service.CourseBaseInfoService;
import com.enjoylearning.content.service.CoursePublishService;
import com.enjoylearning.content.service.TeachPlanService;
import com.enjoylearning.messagesdk.model.po.MqMessage;
import com.enjoylearning.messagesdk.service.MqMessageService;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    private CourseBaseInfoService courseBaseInfoService;
    @Autowired
    private TeachPlanService teachPlanService;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CoursePublishMapper coursePublishMapper;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private MediaServiceClient mediaServiceClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient  redissonClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        CourseBaseInfoDto courseBase = courseBaseInfoService.selectById(courseId);
        List<TeachplanDto> teachPlanTree = teachPlanService.selectTeachplanById(courseId);
        coursePreviewDto.setCourseBase(courseBase);
        coursePreviewDto.setTeachplans(teachPlanTree);
        return coursePreviewDto;
    }

    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {
        //如果课程信息表状态为已提交则不允许提交
        CourseBaseInfoDto courseBase = courseBaseInfoService.selectById(courseId);
        if (courseBase == null) {
            XueChengPlusException.cast("找不到课程");
        }
        if (courseBase.getAuditStatus().equals("202003")){
            XueChengPlusException.cast("课程正在审核中");
        }
        //检查课程信息内容完整性
        if (null == courseBase.getPic()){
            XueChengPlusException.cast("请先上传课程图片");
        }
        if (teachPlanService.selectTeachplanById(courseId) == null) {
            XueChengPlusException.cast("课程计划不能为空");
        }
        //查询课程基本信息、营销信息等信息插入到预发布表
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBase, coursePublishPre);
        coursePublishPre.setCompanyId(companyId);
        //营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        String courseMarketJson = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(courseMarketJson);
        //计划信息
        List<TeachplanDto> teachPlanTree = teachPlanService.selectTeachplanById(courseId);
        String teachPlanTreeJson = JSON.toJSONString(teachPlanTree);
        coursePublishPre.setTeachplan(teachPlanTreeJson);
        //修改基本信息表状态为已提交
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
        coursePublishPre.setStatus("202003");
        coursePublishPre.setAuditDate(LocalDateTime.now());
        System.out.println(courseBase);
        System.out.println(coursePublishPre);
        //插入预提交表
        if (coursePublishPreMapper.selectOne(new LambdaQueryWrapper<CoursePublishPre>().eq(CoursePublishPre::getId, courseId)) != null) {
            coursePublishPreMapper.updateById(coursePublishPre);
        }else {
            coursePublishPreMapper.insert(coursePublishPre);
        }
    }

    @Override
    public void publish(Long companyId, Long courseId) {
        //将预发布表的信息拷贝到发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (null == coursePublishPre) {
            XueChengPlusException.cast("该课程未审核");
        }
        if (!coursePublishPre.getStatus().equals("202004")){
            //课程审核未通过
            XueChengPlusException.cast("该课程审核未通过");
        }
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        //先查询，不存在则添加
        CoursePublish coursePublish1 = coursePublishMapper.selectById(courseId);
        if (null == coursePublish1){
            coursePublishMapper.insert(coursePublish);
        }else {
            coursePublishMapper.updateById(coursePublish);
        }
        //向消息表写入数据
        //mqMessageService.addMessage("course_publish",String.valueOf(courseId),null,null);
        saveCoursePublishMessage(courseId);
        //删除预发布表信息
        coursePublishPreMapper.deleteById(courseId);
    }

    @Override
    public File generateCourseHtml(Long courseId) {
        //静态化文件
        File htmlFile  = null;

        try {
            //配置freemarker
            freemarker.template.Configuration configuration = new freemarker.template.Configuration(freemarker.template.Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}",e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }

        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.upload(multipartFile, "course/"+courseId+".html");
        if(course==null){
            XueChengPlusException.cast("上传静态文件异常");
        }
    }

    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        //从数据库中查询
        return coursePublishMapper.selectById(courseId);
    }

    @Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        //缓存中存在
        if (jsonObj != null){
            //直接返回数据
            String jsonString = jsonObj.toString();
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        }
        RLock lock = redissonClient.getLock("coursequerylock" + courseId);
        lock.lock();
        try {
            //再次查询一次
            Object jsonObjAgain = redisTemplate.opsForValue().get("course:" + courseId);
            if (jsonObjAgain != null) {
                //直接返回数据
                String jsonString = jsonObjAgain.toString();
                CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
                return coursePublish;
            }
            //从数据库中取
            CoursePublish coursePublish = getCoursePublish(courseId);
            if (coursePublish != null) {
                //查询完成后再存储到redis
                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish));
            }
            return coursePublish;
        }  finally {
            lock.unlock();
        }
    }

    private void saveCoursePublishMessage(Long courseId){
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if(mqMessage==null){
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }
}
